<?php

namespace Action\Flow\GenericFlow\Item\Join;

class Link extends \Library\Action\UserAction 
	implements \Library\Action\AjaxAction {
	
	private $_content;
	private $_link;
	private $_charset = 'UTF-8';

	public function execute() {
		parent::execute();

		$link = trim($this->getParam( 'link' ));
		
		_a( $link ? true : false,  'Empty link' );
		
		if( !preg_match( '/^(http|ftp):\/\//is', $link ) ) {
			$link = 'http://' . $link;
		}
		
		_c( 'Url', $link );
		
		_a( ($this->_content = @$this->_fileGetContents( $link )) ? true : false, 'Invalid url' );

		if( $title = $this->_getMetaProperty( 'og:title' ) ) {
			$data = array(
				'title' => $title,
				'type' => $this->_getMetaProperty( 'og:type' ),
				'site_name' => $this->_getMetaProperty( 'og:site_name' ),
				'url' => $this->_getMetaProperty( 'og:url' ),
				'image' => $this->_getMetaProperty( 'og:image' ),
				'description' =>  $this->_getMetaProperty( 'og:description' )
			);
		}
		else {
			$description = $this->_getMetaByKey( 'name', 'description' );
			$data = array(
				'title' => $this->_getTag( 'title' ),
				'type' => 'website',
				'url' => $link,
				'site_name' => parse_url( $link, PHP_URL_HOST ),
				'image' => 'http://open.thumbshots.org/image.pxf?url='  . urlencode($link),
				'description' => $description ?: 'No description available'
			);
		}
		
		$this->_link = new \Bean\Db\Link( $data );
		
		return array(
			'data' => $data,
			'content' => $this->view()
		);
	}
	
	public function getLink() {
		return $this->_link;
	}
	
	private function _getMetaProperty( $key ) {
		return $this->_getMetaByKey( 'property', $key );
	}
	
	private function _getMetaByKey( $keyName, $keyValue ) {
		if( preg_match( '/<meta\s+' . $keyName . '="' . $keyValue . '"\s+content="((?:[^"\\\]|\\\.)*)"/is', $this->_content, $matches ) ) {
			return $this->_decode( $matches[1] );
		}
		return null;
	}
	
	private function _getTag( $key ) {
		if( preg_match( '/<' . $key . '>(.*?)<\/' . $key . '>/is', $this->_content, $matches ) ) {
			return $this->_decode( $matches[1] );
		}
		return null;
	}
	
	private function _decode( $str ) {
		return html_entity_decode( $str, ENT_COMPAT, $this->_charset );
	}
	
	private function _fileGetContents( $url ) {
		$content = file_get_contents($url); 
		return mb_convert_encoding($content, 'UTF-8', 
			mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true) ); 
	}
}
